﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Project.Core.Config.Common.Utils;
using System.Diagnostics;
using System.Reflection;

namespace Project.Core.Config.Config.Autofac {
    public static class BuilderAutofacExtensions {
        public static void AddAutofacBuilder(this WebApplicationBuilder builder) {
            Debug.WriteLine("配置Autofac");

            // 获取外部程序集的文件名或路径
            //var assemblyNames = builder.Configuration.GetSection("ExternalAssembly").GetChildren().Select(x => x.Value).ToArray();
            var assemblyNames = AppHelper.ReadAppSettings("Autofac", new string[] { "ExternalAssembly" });

            //使用autofac的容器工厂替换系统默认的容器
            builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            //替换控制器的所有者( 没有这一步controller中不能使用属性注入)
            builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
            builder.Host.ConfigureContainer<ContainerBuilder>((hostContext, configure) => {
                // 加载外部程序集的所有controller进行注册，并使用属性注入功能
                foreach (var name in assemblyNames) {
                    var externalAssembly = Assembly.Load(name).GetExportedTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
                    configure.RegisterTypes(externalAssembly).PropertiesAutowired();
                }
                //加载本程序集，找到所有的controller进行注册，并使用属性注入功能
                //var controllerTypesInassembly = typeof(Program).Assembly.GetExportedTypes()
                //    .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
                //configure.RegisterTypes(controllerTypesInassembly).PropertiesAutowired();

                configure.RegisterModule(new AutofacModule(assemblyNames));
                //configure.RegisterModule<AutofacModule>();
            });
        }

    }
}
